package a01_数组;

import java.util.Arrays;

/**
 * <p>
 * a03_有序数组的平方
 * </p>
 *
 * @author flyduck
 * @since 2024-06-12
 */
public class a04_有序数组的平方复习4 {

    public static void main(String[] args) {
        int[] nums = {-4,-1,0,3,10};
        int[] result = sortedSquares(nums);
        System.out.println("result = " + Arrays.toString(result));
    }


    public static int[] sortedSquares(int[] nums) {
        int[] newArray = new int[nums.length];
        int leftIdx = 0;
        int rightIdx = nums.length - 1;

        int lastIdx = newArray.length - 1;

        while (leftIdx <= rightIdx) {
            if((nums[leftIdx] * nums[leftIdx]) >= (nums[rightIdx] * nums[rightIdx])){
                newArray[lastIdx] = nums[leftIdx] * nums[leftIdx];
                leftIdx++;
                lastIdx--;
            }else {
                newArray[lastIdx] = nums[rightIdx] * nums[rightIdx];
                rightIdx--;
                lastIdx--;
            }
        }
        return newArray;
    }
}
